package il.technion.cs236369.proxy;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;

import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;

import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Named;

public class HttpProxy extends AbstractHttpProxy
{
	@Inject
	HttpProxy(SocketFactory sockFactory, ServerSocketFactory srvSockFactory,
			@Named("httproxy.net.port") int port,
			@Named("httproxy.db.url") String dbURL,
			@Named("httproxy.db.name") String dbName,
			@Named("httproxy.db.table") String tblName,
			@Named("httproxy.db.username") String dbUsername,
			@Named("httproxy.db.password") String dbPassword,
			@Named("httproxy.db.driver") String dbDriver)
			throws ClassNotFoundException
	{
		super(sockFactory, srvSockFactory, 
			  port, dbURL, dbName, tblName,
			  dbUsername, dbPassword, dbDriver);

		try 
		{
			m_cacheManager = new CacheManager(dbDriver, dbURL, dbName, tblName, dbUsername,	dbPassword);
		} 
		catch (SQLException e) 
		{
			System.err.println("Error while tring to connect to the cache table. Not Using cache");
			m_cacheManager = null;
		}
	}

	private HttpServer m_server;
	private CacheManager m_cacheManager;

	@Override
	public void bind() throws IOException 
	{
		m_server = new HttpServer(srvSockFactory, port,
								  new RequestHandler(sockFactory, m_cacheManager));
	}

	@Override
	public void start() 
	{
		while (true) 
		{
			try 
			{
				m_server.getNewHttpRequest(); 
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			} 
		}

	}

	public static void main(String[] args) throws Exception
	{
		Properties p = new Properties();
		p.load(new FileInputStream("config"));
		Injector inj = Guice.createInjector(new HttpProxyModule(p));
		IHttpProxy proxy = inj.getInstance(HttpProxy.class);
		proxy.bind();
		proxy.start();
	}
	
}
